package com.redis.springtest;

import com.redis.springtest.config.RedisConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2020 -04-21 下午4:52
 */
@Slf4j
public class AppRedisString {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(RedisConfig.class);
        final RedisTemplate redisTemplate = ctx.getBean(RedisTemplate.class);

        final ValueOperations valueOperations = redisTemplate.opsForValue();
        // 设值
        valueOperations.set("key1", "value2");
        valueOperations.set("key2", "value2");

        // 通过key获取值
        final String v1 = (String) valueOperations.get("key1");
        log.info("get value - {} from redis by key1", v1);

        // 通过key删除值
        final Boolean delete = redisTemplate.delete("key1");
        log.info("delete key1 from redis, success?{}", delete);

        // 求长度
        final Long size = valueOperations.size("key2");
        log.info("value length for key2 is {}", size);

        // 设置新值并返回旧值
        final String oldValue = (String) valueOperations.getAndSet("key2", "new_value2");
        log.info("get old value for key2 is {}", oldValue);

        // 通过key获取值
        log.info("get new value for key2 is {}", valueOperations.get("key2"));

        // 求子串
        final String rangeValue = valueOperations.get("key2", 0, 3);
        log.info(rangeValue);

        // 追加字符串到末尾，返回新的字符串长度
        final Integer append = valueOperations.append("key2", "_app");
        log.info("padding string to key2 and new size for value is {}", append);
        log.info("after padding, string is {}", valueOperations.get("key2"));
    }
}
